难以理解C++中的->重载问题

来源:百度知道 编辑:UC知道 时间:2024/05/28 18:07:58
我还是把程序发完吧
template <class Node>
struct node_swap{
Node *ptr;

node_swap(Node *p=0):ptr(p){}
Node& operator*()const {return *ptr;}
Node* operator->()const {return ptr;}

node_swap& operator++() {ptr=ptr->next;return *this;}
node_swap operator++(int) {node_swap tmp=*this;++*this;return tmp;}

bool operator==(const node_swap& i) const {return ptr==i.ptr;}
bool operator!=(const node_swap& i) const {return ptr!=i.ptr;}
};
Struct Node{
int val;
int_node* next;
};
我是在定义一个STL的Input Iterators,我想知道应该怎样理解这个->的重载,到底这个"->"是指的"P->",还是"->P"?

不太理解你问的问题,当然是"P->"啦

->操作符在c++中规定了重载时必须定义为类成员操作符。类成员的操作符重载时左操作数是该类的对象,因此这里->的重载使用的时候是P->。
当操作符重载是非类成员时,则函数参数中的第1个参数是左操作数,第2个参数是右操作数。
如:重载operator<<时分别用2种不同的方式重载
class type
{
friend ostream& operator<<(ostream &os, const type &t);
/*或者
public:
ostream& operator<<(ostream &os);*/
...
}
使用时:
type t;
cout<<t;//使用第1种方式定义的
t<<cout;//使用第2种方式定义的
ps:由于第2种方式和常规相违,所以通常都是以非类成员方式重载operator<<。但是有4种操作符规定了必须定义为类成员,包括前面提到的->,还有= [] ()这3个。